<template>
    <div class="product-container">
        <!-- 面包屑导航 -->
        <div class="breadcrumb">
            <span>首页</span>
            <span class="separator">/</span>
            <span>产品</span>
            <el-icon class="close-icon" @click="$router.go(-1)">
                <Close />
            </el-icon>
        </div>

        <!-- 标题 -->
        <div class="page-title">
            <el-icon>
                <Box />
            </el-icon>
            <span>产品管理</span>
        </div>

        <!-- 搜索和操作区域 -->
        <div class="search-action-bar">
            <div class="search-fields">
                <el-input v-model="searchForm.productCode" placeholder="产品编号" clearable
                    style="width: 200px; margin-right: 10px;" />
                <el-input v-model="searchForm.productName" placeholder="产品名称" clearable
                    style="width: 200px; margin-right: 10px;" />
                <el-select v-model="searchForm.productAttribute" placeholder="产品属性" clearable
                    style="width: 150px; margin-right: 10px;">
                    <el-option label="自制" value="自制" />
                    <el-option label="外购" value="外购" />
                    <el-option label="委外" value="委外" />
                </el-select>
            </div>
            <div class="action-buttons">
                <el-button type="primary" @click="handleSearch">
                    <el-icon>
                        <Search />
                    </el-icon>
                    查询
                </el-button>
                <el-button @click="handleReset">
                    <el-icon>
                        <Refresh />
                    </el-icon>
                    重置
                </el-button>
                <el-button type="success" @click="handleAdd">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    新建
                </el-button>
                
                <el-button type="success" @click="handleExport">
                    <el-icon>
                        <Download />
                    </el-icon>
                    导出
                </el-button>
                <el-button type="info" @click="handleQuickExport" :loading="exportLoading">
                    <el-icon>
                        <Download />
                    </el-icon>
                    快速导出
                </el-button>
                
            </div>
        </div>

        <!-- 主表格：产品列表 -->
        <div class="main-table">
            <el-table :data="productList" @row-click="handleRowClick" @selection-change="handleSelectionChange"
                highlight-current-row v-loading="loading" style="width: 100%">
                <el-table-column type="selection" width="55" />
                <el-table-column type="index" label="#" width="60" />
                <el-table-column prop="productCode" label="产品编号" width="150" />
                <el-table-column prop="productName" label="产品名称" width="200" />
                <el-table-column prop="productSpec" label="产品规格" width="150" />
                <el-table-column prop="inventoryUnit" label="库存单位" width="100" />
                <el-table-column prop="productAttribute" label="产品属性" width="100" />
                <el-table-column prop="productImage" label="产品图片" width="100">
                    <template #default="scope">
                        <el-image v-if="scope.row.productImage" :src="getImageUrl(scope.row.productImage)"
                            :preview-src-list="[getImageUrl(scope.row.productImage)]" fit="cover"
                            style="width: 40px; height: 40px">
                            <template #error>
                                <div class="image-placeholder">图片</div>
                            </template>
                        </el-image>
                        <div v-else class="image-placeholder">图片</div>
                    </template>
                </el-table-column>
                <el-table-column prop="currentInventory" label="当前库存" width="100" />
                <el-table-column prop="maxInventory" label="最大库存" width="100" />
                <el-table-column prop="minInventory" label="最小库存" width="100" />
                <el-table-column prop="safetyInventory" label="安全库存" width="100" />
                <el-table-column prop="createTime" label="创建时间" width="180">
                    <template #default="scope">
                        {{ formatDateTime(scope.row.createTime) }}
                    </template>
                </el-table-column>
                <el-table-column prop="creator" label="创建人" width="100" />
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click.stop="handleEdit(scope.row)">
                            <el-icon><Edit /></el-icon>
                            编辑
                        </el-button>
                        <el-button type="danger" size="small" @click.stop="handleDelete(scope.row)">
                            <el-icon><Delete /></el-icon>
                            删除
                        </el-button>
                    </template>
                </el-table-column>

            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination v-model:current-page="pagination.pageIndex" v-model:page-size="pagination.pageSize"
                    :page-sizes="[10, 20, 30, 50, 100]" :total="pagination.total"
                    layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </div>

        <!-- 产品编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑产品' : '新建产品'" width="800px" :close-on-click-modal="false"
            @close="handleDialogClose">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px"
                style="max-height: 600px; overflow-y: auto;">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="产品编号" prop="productCode">
                            <div style="display: flex; gap: 8px;">
                                <el-input v-model="form.productCode" placeholder="请输入产品编号" :disabled="isEdit"
                                    @blur="handleProductCodeBlur" style="flex: 1;" />
                                <el-button v-if="!isEdit" type="primary" @click="generateProductCode"
                                    :loading="generatingCode" style="width: 80px;">
                                    生成
                                </el-button>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="产品名称" prop="productName">
                            <el-input v-model="form.productName" placeholder="请输入产品名称" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="产品规格" prop="productSpec">
                            <el-input v-model="form.productSpec" placeholder="请输入产品规格" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="库存单位" prop="inventoryUnit">
                            <el-input v-model="form.inventoryUnit" placeholder="请输入库存单位" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="产品属性" prop="productAttribute">
                            <el-select v-model="form.productAttribute" placeholder="请选择产品属性" style="width: 100%">
                                <el-option label="自制" value="自制" />
                                <el-option label="外购" value="外购" />
                                <el-option label="委外" value="委外" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="工艺路线" prop="processRouteId">
                            <el-select v-model="form.processRouteId" placeholder="请选择工艺路线" clearable style="width: 100%"
                                :loading="processRouteLoading">
                                <el-option v-for="route in processRouteOptions" :key="route.processRouteId"
                                    :label="`${route.routeCode} - ${route.routeName}`" :value="route.processRouteId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="最大库存" prop="maxInventory">
                            <el-input-number v-model="form.maxInventory" :min="0" style="width: 100%"
                                placeholder="最大库存" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="最小库存" prop="minInventory">
                            <el-input-number v-model="form.minInventory" :min="0" style="width: 100%"
                                placeholder="最小库存" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="安全库存" prop="safetyInventory">
                            <el-input-number v-model="form.safetyInventory" :min="0" style="width: 100%"
                                placeholder="安全库存" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="当前库存" prop="currentInventory">
                            <el-input-number v-model="form.currentInventory" :min="0" style="width: 100%"
                                placeholder="当前库存" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="产品图片" prop="productImage">
                            <div class="image-upload-section">
                                <el-upload ref="uploadRef" class="avatar-uploader" action="#" :auto-upload="false"
                                    :show-file-list="false" :on-change="handleImageChange" accept="image/*"
                                    style="width: 100%">
                                    <img v-if="form.productImage" :src="getImageUrl(form.productImage)" class="avatar"
                                        alt="产品图片" />
                                    <el-icon v-else class="avatar-uploader-icon">
                                        <Plus />
                                    </el-icon>
                                </el-upload>
                                <div class="upload-tip">支持JPG、PNG、GIF、BMP、WebP等格式，文件大小不超过10MB</div>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                        {{ isEdit ? '更新' : '创建' }}
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 库存更新对话框 -->
        <el-dialog v-model="inventoryDialogVisible" title="更新产品库存" width="400px" :close-on-click-modal="false">
            <el-form ref="inventoryFormRef" :model="inventoryForm" :rules="inventoryRules" label-width="100px">
                <el-form-item label="产品名称">
                    <span>{{ selectedRow?.productName }}</span>
                </el-form-item>
                <el-form-item label="当前库存" prop="currentInventory">
                    <el-input-number v-model="inventoryForm.currentInventory" :min="0" style="width: 100%"
                        placeholder="请输入库存数量" />
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="inventoryDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleUpdateInventory" :loading="inventorySubmitLoading">
                        更新
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 导出对话框 -->
        <el-dialog v-model="exportDialogVisible" title="导出产品数据" width="500px" :close-on-click-modal="false">
            <el-form :model="exportForm" label-width="120px">
                <el-form-item label="导出范围">
                    <el-radio-group v-model="exportForm.exportType">
                        <el-radio label="all">全部数据</el-radio>
                        <el-radio label="current">当前页数据</el-radio>
                        <el-radio label="selected" :disabled="selectedRows.length === 0">
                            选中数据 ({{ selectedRows.length }}条)
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="导出字段">
                    <el-checkbox-group v-model="exportForm.fields">
                        <el-checkbox label="productCode">产品编号</el-checkbox>
                        <el-checkbox label="productName">产品名称</el-checkbox>
                        <el-checkbox label="productSpec">产品规格</el-checkbox>
                        <el-checkbox label="inventoryUnit">库存单位</el-checkbox>
                        <el-checkbox label="productAttribute">产品属性</el-checkbox>
                        <el-checkbox label="currentInventory">当前库存</el-checkbox>
                        <el-checkbox label="maxInventory">最大库存</el-checkbox>
                        <el-checkbox label="minInventory">最小库存</el-checkbox>
                        <el-checkbox label="safetyInventory">安全库存</el-checkbox>
                        <el-checkbox label="createTime">创建时间</el-checkbox>
                        <el-checkbox label="creator">创建人</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="文件格式">
                    <el-radio-group v-model="exportForm.format">
                        <el-radio label="xlsx">Excel (.xlsx)</el-radio>
                        <el-radio label="csv">CSV (.csv)</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="exportDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleExportConfirm" :loading="exportLoading">
                        确认导出
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import {
    Search,
    Refresh,
    Plus,
    Edit,
    Delete,
    Close,
    Box,
    Download
} from '@element-plus/icons-vue'
import {
    getAllProducts,
    getProductList,
    createProduct,
    updateProduct,
    deleteProduct,
    batchDeleteProducts,
    checkProductCodeExists,
    getAllProcessRoutes,
    updateProductInventory,
    type Product,
    type ProductCreateDTO,
    type ProductUpdateDTO,
    type ProcessRouteOption,
    type ProductSearchParams
} from '@/api/product'
import { MES_XSP_ApiHost } from '@/utils/Interceptors'

// 尝试导入xlsx库，如果不存在则使用CSV导出
let XLSX: any = null
try {
    XLSX = require('xlsx')
} catch (error) {
    console.log('xlsx库未安装，将使用CSV导出')
}

// 响应式数据
const productList = ref<Product[]>([])
const selectedRow = ref<Product | null>(null)
const selectedRows = ref<Product[]>([])
const dialogVisible = ref(false)
const inventoryDialogVisible = ref(false)
const exportDialogVisible = ref(false)
const isEdit = ref(false)
const loading = ref(false)
const submitLoading = ref(false)
const inventorySubmitLoading = ref(false)
const processRouteLoading = ref(false)
const generatingCode = ref(false)
const isGeneratingCode = ref(false) // 添加标志，避免在生成时触发检查
const exportLoading = ref(false)

// 选项数据
const processRouteOptions = ref<ProcessRouteOption[]>([])

// 搜索表单
const searchForm = reactive({
    productCode: '',
    productName: '',
    productAttribute: ''
})

// 分页数据
const pagination = reactive({
    pageIndex: 1,
    pageSize: 30,
    total: 0
})

// 表单数据
const form = reactive({
    productId: 0,
    productCode: '',
    productName: '',
    productSpec: '',
    inventoryUnit: '',
    productAttribute: '',
    processRouteId: undefined as number | undefined,
    maxInventory: undefined as number | undefined,
    minInventory: undefined as number | undefined,
    safetyInventory: undefined as number | undefined,
    currentInventory: 0,
    productImage: ''
})

// 库存更新表单
const inventoryForm = reactive({
    currentInventory: 0
})

// 导出表单
const exportForm = reactive({
    exportType: 'current', // all, current, selected
    fields: [
        'productCode',
        'productName',
        'productSpec',
        'inventoryUnit',
        'productAttribute',
        'currentInventory',
        'maxInventory',
        'minInventory',
        'safetyInventory',
        'createTime',
        'creator'
    ],
    format: 'xlsx' // xlsx, csv
})

// 表单验证规则
const rules = {
    productCode: [
        { required: true, message: '请输入产品编号', trigger: 'blur' },
        { min: 2, max: 50, message: '产品编号长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    productName: [
        { required: true, message: '请输入产品名称', trigger: 'blur' },
        { min: 2, max: 100, message: '产品名称长度在 2 到 100 个字符', trigger: 'blur' }
    ],
    inventoryUnit: [
        { required: true, message: '请输入库存单位', trigger: 'blur' }
    ],
    productAttribute: [
        { required: true, message: '请选择产品属性', trigger: 'change' }
    ]
}

// 库存表单验证规则
const inventoryRules = {
    currentInventory: [
        { required: true, message: '请输入库存数量', trigger: 'blur' },
        { type: 'number', min: 0, message: '库存数量不能小于0', trigger: 'blur' }
    ]
}

// 表单引用
const formRef = ref()
const inventoryFormRef = ref()

// 计算属性
const dialogTitle = computed(() => {
    return isEdit.value ? '编辑产品' : '新建产品'
})

// 方法
const fetchData = async () => {
    try {
        loading.value = true
        const params: ProductSearchParams = {
            pageIndex: pagination.pageIndex,
            pageSize: pagination.pageSize,
            productCode: searchForm.productCode || undefined,
            productName: searchForm.productName || undefined
        }

        const response = await getProductList(params)
        if (response.data.code === 200) {
            productList.value = response.data.pageData
            pagination.total = response.data.totalCount
        } else {
            ElMessage.error(response.data.msg || '获取产品列表失败')
        }
    } catch (error) {
        console.error('获取产品列表失败:', error)
        ElMessage.error('获取产品列表失败')
    } finally {
        loading.value = false
    }
}

const fetchProcessRoutes = async () => {
    try {
        processRouteLoading.value = true
        const response = await getAllProcessRoutes()
        if (response.data.code === 200) {
            processRouteOptions.value = response.data.data
        } else {
            ElMessage.error(response.data.msg || '获取工艺路线失败')
        }
    } catch (error) {
        console.error('获取工艺路线失败:', error)
        ElMessage.error('获取工艺路线失败')
    } finally {
        processRouteLoading.value = false
    }
}

const handleSearch = () => {
    pagination.pageIndex = 1
    fetchData()
}

const handleReset = () => {
    searchForm.productCode = ''
    searchForm.productName = ''
    searchForm.productAttribute = ''
    pagination.pageIndex = 1
    fetchData()
}

const handleSizeChange = (size: number) => {
    pagination.pageSize = size
    pagination.pageIndex = 1
    fetchData()
}

const handleCurrentChange = (page: number) => {
    pagination.pageIndex = page
    fetchData()
}

const handleRowClick = (row: Product) => {
    selectedRow.value = row
}

const handleSelectionChange = (selection: Product[]) => {
    selectedRows.value = selection
}

const resetForm = () => {
    Object.assign(form, {
        productId: 0,
        productCode: '',
        productName: '',
        productSpec: '',
        inventoryUnit: '',
        productAttribute: '',
        processRouteId: undefined,
        maxInventory: undefined,
        minInventory: undefined,
        safetyInventory: undefined,
        currentInventory: 0,
        productImage: ''
    })
}

const handleAdd = () => {
    console.log('=== 开始新建产品 ===')
    isEdit.value = false
    resetForm()
    console.log('表单重置完成，productCode:', form.productCode)
    dialogVisible.value = true
    console.log('对话框已显示')

    // 使用nextTick确保DOM更新完成后再生成产品编号
    nextTick(() => {
        console.log('DOM更新完成，开始生成产品编号')
        generateProductCode()
    })
}

const handleEdit = (row?: Product) => {
    console.log('=== 开始编辑产品 ===')
    console.log('传入的row参数:', row)
    console.log('当前selectedRow:', selectedRow.value)
    
    const targetRow = row || selectedRow.value
    if (!targetRow) {
        ElMessage.warning('请选择要编辑的产品')
        return
    }

    console.log('目标行数据:', targetRow)
    
    // 设置编辑状态
    isEdit.value = true
    
    // 直接设置表单数据，不使用Object.assign
    form.productId = targetRow.productId
    form.productCode = targetRow.productCode
    form.productName = targetRow.productName
    form.productSpec = targetRow.productSpec || ''
    form.inventoryUnit = targetRow.inventoryUnit
    form.productAttribute = targetRow.productAttribute
    form.processRouteId = targetRow.processRouteId
    form.maxInventory = targetRow.maxInventory
    form.minInventory = targetRow.minInventory
    form.safetyInventory = targetRow.safetyInventory
    form.currentInventory = targetRow.currentInventory || 0
    form.productImage = targetRow.productImage || ''
    
    console.log('表单数据已设置:', form)
    console.log('form.productCode:', form.productCode)
    console.log('form.productName:', form.productName)
    console.log('form.productAttribute:', form.productAttribute)
    
    // 使用nextTick确保DOM更新完成后再显示对话框
    nextTick(() => {
        dialogVisible.value = true
        console.log('对话框已显示')
        
        // 检查表单验证状态
        if (formRef.value) {
            console.log('表单引用存在')
            // 延迟检查表单验证状态
            setTimeout(() => {
                console.log('检查表单验证状态...')
                formRef.value?.validate((valid: boolean) => {
                    console.log('表单验证结果:', valid)
                })
            }, 200)
        }
        
        // 延迟测试表单数据
        setTimeout(() => {
            testFormData()
        }, 100)
    })
}

const handleDelete = async (row?: Product) => {
    const targetRow = row || selectedRow.value
    if (!targetRow) {
        ElMessage.warning('请选择要删除的产品')
        return
    }

    try {
        await ElMessageBox.confirm(
            `确定要删除产品 "${targetRow.productName}" 吗？`,
            '确认删除',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        const response = await deleteProduct(targetRow.productId)
        if (response.data.code === 200) {
            ElMessage.success('删除成功')
            if (selectedRow.value?.productId === targetRow.productId) {
                selectedRow.value = null
            }
            fetchData()
        } else {
            ElMessage.error(response.data.msg || '删除失败')
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除产品失败:', error)
            ElMessage.error('删除产品失败')
        }
    }
}

const handleBatchDelete = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要删除的产品')
        return
    }

    try {
        await ElMessageBox.confirm(
            `确定要删除选中的 ${selectedRows.value.length} 个产品吗？`,
            '确认批量删除',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        const productIds = selectedRows.value.map(row => row.productId)
        const response = await batchDeleteProducts(productIds)
        if (response.data.code === 200) {
            ElMessage.success('批量删除成功')
            selectedRows.value = []
            selectedRow.value = null
            fetchData()
        } else {
            ElMessage.error(response.data.msg || '批量删除失败')
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('批量删除产品失败:', error)
            ElMessage.error('批量删除产品失败')
        }
    }
}

// 自动生成产品编号
const generateProductCode = () => {
    console.log('=== 开始生成产品编号 ===')

    // 立即设置加载状态
    generatingCode.value = true
    isGeneratingCode.value = true

    // 使用setTimeout确保在下一个事件循环中执行
    setTimeout(() => {
        try {
            // 获取当前时间
            const now = new Date()
            const year = now.getFullYear()
            const month = String(now.getMonth() + 1).padStart(2, '0')
            const day = String(now.getDate()).padStart(2, '0')
            const hour = String(now.getHours()).padStart(2, '0')
            const minute = String(now.getMinutes()).padStart(2, '0')
            const second = String(now.getSeconds()).padStart(2, '0')

            // 生成三位随机数 (100-999)
            const randomNum = Math.floor(Math.random() * 900) + 100

            // 组合产品编号：CP + 年月日时分秒 + 三位随机数
            const productCode = `CP${year}${month}${day}${hour}${minute}${second}${randomNum}`

            console.log('生成的产品编号:', productCode)
            console.log('编号长度:', productCode.length)

            // 设置表单值
            form.productCode = productCode
            console.log('表单产品编号已设置:', form.productCode)

            // 显示成功消息
            ElMessage.success(`产品编号生成成功：${productCode}`)
            console.log('=== 产品编号生成完成 ===')

        } catch (error) {
            console.error('生成产品编号失败:', error)
            ElMessage.error('生成产品编号失败，请重试')
        } finally {
            // 重置状态
            generatingCode.value = false
            setTimeout(() => {
                isGeneratingCode.value = false
            }, 100)
        }
    }, 0)
}

// 简单的测试生成方法
const testGenerateCode = () => {
    try {
        const now = new Date()
        const year = now.getFullYear()
        const month = String(now.getMonth() + 1).padStart(2, '0')
        const day = String(now.getDate()).padStart(2, '0')
        const hour = String(now.getHours()).padStart(2, '0')
        const minute = String(now.getMinutes()).padStart(2, '0')
        const second = String(now.getSeconds()).padStart(2, '0')
        const randomNum = Math.floor(Math.random() * 900) + 100

        const testCode = `CP${year}${month}${day}${hour}${minute}${second}${randomNum}`
        console.log('✅ 测试生成的产品编号:', testCode)
        console.log('✅ 编号长度:', testCode.length)
        console.log('✅ 编号格式验证:', /^CP\d{17}$/.test(testCode))

        return testCode
    } catch (error) {
        console.error('❌ 测试生成失败:', error)
        return null
    }
}

const handleProductCodeBlur = async () => {
    // 如果正在生成编号，则不执行检查
    if (isGeneratingCode.value || !form.productCode || isEdit.value) return

    try {
        const response = await checkProductCodeExists(form.productCode)
        if (response.data.code === 200 && response.data.data) {
            ElMessage.warning('产品编号已存在，请使用其他编号')
        }
    } catch (error) {
        console.error('检查产品编号失败:', error)
    }
}

const handleSubmit = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()
        submitLoading.value = true

        if (isEdit.value) {
            const updateData: ProductUpdateDTO = {
                productId: form.productId,
                productCode: form.productCode,
                productName: form.productName,
                productSpec: form.productSpec || undefined,
                inventoryUnit: form.inventoryUnit,
                productAttribute: form.productAttribute,
                processRouteId: form.processRouteId,
                maxInventory: form.maxInventory,
                minInventory: form.minInventory,
                safetyInventory: form.safetyInventory,
                currentInventory: form.currentInventory,
                productImage: form.productImage || undefined,
                modifier: 'Admin'
            }

            const response = await updateProduct(updateData)
            if (response.data.code === 200) {
                ElMessage.success('更新成功')
                dialogVisible.value = false
                fetchData()
            } else {
                ElMessage.error(response.data.msg || '更新失败')
            }
        } else {
            const createData: ProductCreateDTO = {
                productCode: form.productCode,
                productName: form.productName,
                productSpec: form.productSpec || undefined,
                inventoryUnit: form.inventoryUnit,
                productAttribute: form.productAttribute,
                processRouteId: form.processRouteId,
                maxInventory: form.maxInventory,
                minInventory: form.minInventory,
                safetyInventory: form.safetyInventory,
                currentInventory: form.currentInventory,
                productImage: form.productImage || undefined,
                creator: 'Admin'
            }

            const response = await createProduct(createData)
            if (response.data.code === 200) {
                ElMessage.success('创建成功')
                dialogVisible.value = false
                fetchData()
            } else {
                ElMessage.error(response.data.msg || '创建失败')
            }
        }
    } catch (error) {
        console.error('提交表单失败:', error)
        ElMessage.error('操作失败')
    } finally {
        submitLoading.value = false
    }
}

const handleDialogClose = () => {
    console.log('=== 对话框关闭 ===')
    console.log('当前isEdit状态:', isEdit.value)
    
    // 只有在新建模式下才重置表单
    if (!isEdit.value) {
        if (formRef.value) {
            formRef.value.resetFields()
        }
        resetForm()
    }
    
    // 重置编辑状态
    isEdit.value = false
    console.log('对话框关闭完成')
}

// 图片上传处理
const handleImageChange = async (file: any) => {
    try {
        // 验证文件类型
        const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/bmp', 'image/webp']
        if (!allowedTypes.includes(file.raw.type)) {
            ElMessage.error('只支持上传图片文件（JPG、PNG、GIF、BMP、WebP）')
            return
        }

        // 验证文件大小
        if (file.raw.size > 10 * 1024 * 1024) {
            ElMessage.error('图片文件大小不能超过10MB')
            return
        }

        const formData = new FormData()
        formData.append('file', file.raw)

        const response = await MES_XSP_ApiHost.post('/api/FileUpload/UploadImage', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })

        if (response.data.code === 200) {
            form.productImage = response.data.data
            ElMessage.success('图片上传成功')
        } else {
            ElMessage.error(response.data.msg || '图片上传失败')
        }
    } catch (error) {
        console.error('图片上传失败:', error)
        ElMessage.error('图片上传失败')
    }
}

// 获取图片完整URL
const getImageUrl = (imageUrl: string): string => {
    if (!imageUrl) return ''

    // 如果已经是完整URL，直接返回
    if (imageUrl.startsWith('http://') || imageUrl.startsWith('https://')) {
        return imageUrl
    }

    // 如果是相对路径，拼接后端API基础路径
    const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5058'
    const fullUrl = `${baseUrl}${imageUrl}`

    return fullUrl
}

// 库存更新相关方法
const handleUpdateInventoryDialog = () => {
    if (!selectedRow.value) {
        ElMessage.warning('请选择要更新库存的产品')
        return
    }

    inventoryForm.currentInventory = selectedRow.value.currentInventory || 0
    inventoryDialogVisible.value = true
}

const handleUpdateInventory = async () => {
    if (!inventoryFormRef.value || !selectedRow.value) return

    try {
        await inventoryFormRef.value.validate()
        inventorySubmitLoading.value = true

        const response = await updateProductInventory(
            selectedRow.value.productId,
            inventoryForm.currentInventory,
            'Admin'
        )

        if (response.data.code === 200) {
            ElMessage.success('库存更新成功')
            inventoryDialogVisible.value = false
            fetchData()
        } else {
            ElMessage.error(response.data.msg || '库存更新失败')
        }
    } catch (error) {
        console.error('更新库存失败:', error)
        ElMessage.error('更新库存失败')
    } finally {
        inventorySubmitLoading.value = false
    }
}

// 测试表单数据设置
const testFormData = () => {
    console.log('=== 测试表单数据 ===')
    console.log('form对象:', form)
    console.log('form.productCode:', form.productCode)
    console.log('form.productName:', form.productName)
    console.log('form.productAttribute:', form.productAttribute)
    console.log('form.inventoryUnit:', form.inventoryUnit)
    console.log('isEdit:', isEdit.value)
    console.log('dialogVisible:', dialogVisible.value)
}

// 测试编辑功能
const testEditFunction = () => {
    console.log('=== 测试编辑功能 ===')
    console.log('当前selectedRow:', selectedRow.value)
    if (selectedRow.value) {
        handleEdit(selectedRow.value)
    } else {
        ElMessage.warning('请先选择一个产品进行测试编辑')
    }
}

// 导出相关方法
const handleExport = () => {
    exportDialogVisible.value = true
}

// 快速导出当前页数据
const handleQuickExport = async () => {
    try {
        if (productList.value.length === 0) {
            ElMessage.warning('没有数据可导出')
            return
        }
        
        exportLoading.value = true
        
        // 处理导出数据
        const processedData = processExportData(productList.value)
        
        // 导出为CSV（快速导出默认使用CSV格式）
        await exportToCSV(processedData)
        
        ElMessage.success('快速导出成功')
        
    } catch (error) {
        console.error('快速导出失败:', error)
        ElMessage.error('快速导出失败，请重试')
    } finally {
        exportLoading.value = false
    }
}

const handleExportConfirm = async () => {
    try {
        exportLoading.value = true
        
        // 验证导出字段
        if (exportForm.fields.length === 0) {
            ElMessage.warning('请至少选择一个导出字段')
            return
        }
        
        // 获取要导出的数据
        let exportData: Product[] = []
        
        switch (exportForm.exportType) {
            case 'all':
                // 获取全部数据
                await fetchAllDataForExport()
                exportData = productList.value
                break
            case 'current':
                // 当前页数据
                exportData = productList.value
                break
            case 'selected':
                // 选中的数据
                if (selectedRows.value.length === 0) {
                    ElMessage.warning('请选择要导出的数据')
                    return
                }
                exportData = selectedRows.value
                break
        }
        
        if (exportData.length === 0) {
            ElMessage.warning('没有数据可导出')
            return
        }
        
        // 处理导出数据
        const processedData = processExportData(exportData)
        
        // 执行导出
        if (exportForm.format === 'xlsx') {
            await exportToExcel(processedData)
        } else {
            await exportToCSV(processedData)
        }
        
        ElMessage.success('导出成功')
        exportDialogVisible.value = false
        
    } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败，请重试')
    } finally {
        exportLoading.value = false
    }
}

// 获取全部数据用于导出
const fetchAllDataForExport = async () => {
    try {
        const params: ProductSearchParams = {
            pageIndex: 1,
            pageSize: 10000, // 设置一个较大的值获取全部数据
            productCode: searchForm.productCode || undefined,
            productName: searchForm.productName || undefined
        }
        
        const response = await getProductList(params)
        if (response.data.code === 200) {
            productList.value = response.data.pageData
        } else {
            throw new Error(response.data.msg || '获取数据失败')
        }
    } catch (error) {
        console.error('获取全部数据失败:', error)
        throw error
    }
}

// 处理导出数据
const processExportData = (data: Product[]) => {
    const fieldMap: Record<string, string> = {
        productCode: '产品编号',
        productName: '产品名称',
        productSpec: '产品规格',
        inventoryUnit: '库存单位',
        productAttribute: '产品属性',
        currentInventory: '当前库存',
        maxInventory: '最大库存',
        minInventory: '最小库存',
        safetyInventory: '安全库存',
        createTime: '创建时间',
        creator: '创建人'
    }
    
    // 生成表头
    const headers = exportForm.fields.map(field => fieldMap[field])
    
    // 生成数据行
    const rows = data.map(item => {
        const row: any = {}
        exportForm.fields.forEach(field => {
            switch (field) {
                case 'createTime':
                    row[field] = formatDateTime(item.createTime)
                    break
                default:
                    row[field] = item[field as keyof Product] || ''
            }
        })
        return row
    })
    
    return { headers, rows, data }
}

// 导出为Excel
const exportToExcel = async (exportData: any) => {
    try {
        if (XLSX) {
            // 使用xlsx库导出Excel
            const { headers, rows } = exportData
            
            // 创建工作簿
            const workbook = XLSX.utils.book_new()
            
            // 准备数据
            const excelData = [headers] // 第一行是表头
            rows.forEach((row: any) => {
                const dataRow = exportForm.fields.map(field => row[field] || '')
                excelData.push(dataRow)
            })
            
            // 创建工作表
            const worksheet = XLSX.utils.aoa_to_sheet(excelData)
            
            // 设置列宽
            const colWidths = headers.map(() => ({ width: 15 }))
            worksheet['!cols'] = colWidths
            
            // 添加工作表到工作簿
            XLSX.utils.book_append_sheet(workbook, worksheet, '产品数据')
            
            // 生成文件并下载
            const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
            const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
            
            const link = document.createElement('a')
            const url = URL.createObjectURL(blob)
            
            link.setAttribute('href', url)
            link.setAttribute('download', `产品数据_${new Date().toISOString().slice(0, 10)}.xlsx`)
            link.style.visibility = 'hidden'
            
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            
        } else {
            // 如果没有xlsx库，使用CSV导出
            console.log('xlsx库未安装，使用CSV导出')
            await exportToCSV(exportData)
        }
    } catch (error) {
        console.error('Excel导出失败:', error)
        // 如果Excel导出失败，回退到CSV导出
        console.log('Excel导出失败，回退到CSV导出')
        await exportToCSV(exportData)
    }
}

// 导出为CSV
const exportToCSV = async (exportData: any) => {
    try {
        const { headers, rows } = exportData
        
        // 生成CSV内容
        let csvContent = '\ufeff' // 添加BOM，支持中文
        
        // 添加表头
        csvContent += headers.join(',') + '\n'
        
        // 添加数据行
        rows.forEach((row: any) => {
            const values = exportForm.fields.map(field => {
                const value = row[field] || ''
                // 如果值包含逗号、引号或换行符，需要用引号包围
                if (typeof value === 'string' && (value.includes(',') || value.includes('"') || value.includes('\n'))) {
                    return `"${value.replace(/"/g, '""')}"`
                }
                return value
            })
            csvContent += values.join(',') + '\n'
        })
        
        // 创建下载链接
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
        const link = document.createElement('a')
        const url = URL.createObjectURL(blob)
        
        link.setAttribute('href', url)
        link.setAttribute('download', `产品数据_${new Date().toISOString().slice(0, 10)}.csv`)
        link.style.visibility = 'hidden'
        
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        
    } catch (error) {
        console.error('CSV导出失败:', error)
        throw error
    }
}

// 工具方法
const formatDateTime = (dateTime: string | undefined) => {
    if (!dateTime) return ''
    return new Date(dateTime).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
    fetchData()
    fetchProcessRoutes()

    // 测试生成产品编号功能
    console.log('=== 测试生成产品编号功能 ===')
    testGenerateCode()
})
</script>

<style scoped>
.product-container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

.breadcrumb {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    font-size: 14px;
    color: #666;
}

.breadcrumb .separator {
    margin: 0 8px;
    color: #ccc;
}

.breadcrumb .close-icon {
    margin-left: auto;
    cursor: pointer;
    color: #999;
}

.breadcrumb .close-icon:hover {
    color: #409eff;
}

.page-title {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    font-size: 24px;
    font-weight: bold;
    color: #333;
}

.page-title .el-icon {
    margin-right: 8px;
    font-size: 24px;
    color: #409eff;
}

.search-action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 20px;
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-fields {
    display: flex;
    align-items: center;
}

.action-buttons {
    display: flex;
    gap: 10px;
}

.main-table {
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

.pagination-container {
    display: flex;
    justify-content: center;
    padding: 20px;
    background-color: white;
}

.image-upload-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
}

.avatar-uploader {
    width: 120px;
    height: 120px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: border-color 0.3s;
}

.avatar-uploader:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100%;
    height: 100%;
    text-align: center;
}

.avatar {
    width: 100%;
    height: 100%;
    display: block;
    object-fit: cover;
}

.upload-tip {
    margin-top: 8px;
    font-size: 12px;
    color: #999;
}

.image-placeholder {
    width: 40px;
    height: 40px;
    background-color: #f0f0f0;
    border: 1px solid #d9d9d9;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    color: #999;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .search-action-bar {
        flex-direction: column;
        gap: 15px;
    }

    .search-fields {
        flex-wrap: wrap;
        gap: 10px;
    }

    .action-buttons {
        flex-wrap: wrap;
        justify-content: center;
    }
}
</style>
